const tree = {
    name: '中国',
    children: [
        {
            name: '北京',
            children: [
                {
                    name: '朝阳群众'
                },
                {
                    name: '海淀区'
                },
                {
                    name: '昌平区'
                }
            ]
        },
        {
            name: '浙江省',
            children: [
                {
                    name: '杭州市',
                    code: '0571',
                },
                {
                    name: '嘉兴市'
                },
                {
                    name: '绍兴市'
                },
                {
                    name: '宁波市',
                    code: '1'
                }
            ]
        }
    ]
};

// * 输入name 找code
let res
function traverse(tree,name) {
    if (tree.name === name) res = tree
    if (tree.children) {
        const children = tree.children
        children.forEach(item=>{
            traverse(item,name)
        })
    }
}

traverse(tree, '宁波市')
console.log(res)

// 函数2 在函数内返回
// function getCode(tree, cityName) {
//     if (tree.name === cityName) {
//         return tree.code || null;
//     } else if (tree.children) {
//         for (var i = 0; i < tree.children.length; i++) {
//             var code = getCode(tree.children[i], cityName);
//             if (code) {
//                 return code;
//             }
//         }
//     }
//     return null;
// }

// console.log(getCode(tree, '宁波市'));
